package com.uetoken.cn.fragment;


import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uetoken.cn.R;
import com.uetoken.cn.activity.AboutUsActivity;
import com.uetoken.cn.activity.AccountAndSafeActivity;
import com.uetoken.cn.activity.BankCardActivity;
import com.uetoken.cn.activity.BindYGActivity;
import com.uetoken.cn.activity.FeedBackActivity;
import com.uetoken.cn.activity.LoginActivity;
import com.uetoken.cn.activity.MessageCenterActivity;
import com.uetoken.cn.activity.RegisterActivity;
import com.uetoken.cn.activity.ShippingAddressActivity;
import com.uetoken.cn.activity.UserInfoActivity;
import com.uetoken.cn.activity.WebActivity;
import com.uetoken.cn.adapter.MeItemAdapter;
import com.uetoken.cn.base.BaseFragment;
import com.uetoken.cn.bean.ConfigBean;
import com.uetoken.cn.bean.MeItemBean;
import com.uetoken.cn.bean.MyInfoBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.GlideApp;
import com.uetoken.cn.utils.GlideUtils;
import com.uetoken.cn.utils.UrlUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;

/**
 * @author 谢杨
 * A simple {@link Fragment} subclass.
 * 我
 */
public class MeFragment extends BaseFragment implements WebResponse {

    @BindView(R.id.rl_fragment_me_head_view)
    RelativeLayout mRlHeadview;
    @BindView(R.id.ry_fragment_me)
    RecyclerView mRyMe;
    @BindView(R.id.tv_view_me_foot_exit)
    Button mTvExit;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.titleTv)
    TextView titleTv;

    Unbinder unbinder;

    private MeItemAdapter mAdapter;
    /**
     * 用户是否登录
     */
    private boolean isLogin;
    /**
     * 已登录时显示的view
     */
    private View loggedInView;
    /**
     * 未登录时显示的view
     */
    private View notLoggedInView;
    /**
     * recyclerview底部布局
     */
    private View footView;
    /**
     * 获取我的基本信息的网络请求码
     */
    private static final int NETWORK_GET_MY = 10;

    private List<MeItemBean> mMeItemBeans;
    /**
     * 消息中心所在的位置
     */
    private int messagePosition;
    /**
     * 消息中心的funName
     */
    private String messageFunName;

    public MeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_me, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);

        initView();
        initHeadView();
        initData();
    }

    public void initHeadView() {
        isLogin = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getBoolean(Constant.SP_WHETHER_LOGIN, false);
        if (isLogin) {
            mRlHeadview.removeAllViews();
            //已登录
            loggedInView = LayoutInflater.from(getActivity()).inflate(R.layout.item_logged_in, mRlHeadview, false);
            mRlHeadview.addView(loggedInView);
            final LoggedInViewHolder loggedInViewHolder = new LoggedInViewHolder(loggedInView);
            /**
             * 用户头像地址
             */
            String photoUrl = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_HEAD_PHOTO, "");
            String name = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_NAME, "");
            String mobile = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_MOBILE_NO, "");
            String nodeCode = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_CODE, "");
            GlideApp.with(this).load(photoUrl).apply(GlideUtils.getOptions()).into(loggedInViewHolder.mIvItemLoggedInHead);
            loggedInViewHolder.mTvItemLoggedInNickname.setText(name + "(" + nodeCode + ")");
            if (!TextUtils.isEmpty(mobile)) {
                loggedInViewHolder.mTvItemLoggedInNumber.setText(mobile);
            }

            mTvExit.setVisibility(View.VISIBLE);

            loggedInViewHolder.mLlItemLoggedIn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().startActivity(new Intent(getActivity(), UserInfoActivity.class));
                }
            });
        } else {
            mRlHeadview.removeAllViews();
            //未登录
            notLoggedInView = LayoutInflater.from(getActivity()).inflate(R.layout.item_not_logged_in, mRlHeadview, false);
            mRlHeadview.addView(notLoggedInView);
            NotLoggedInViewHolder notLoggedInViewHolder = new NotLoggedInViewHolder(notLoggedInView);
            notLoggedInViewHolder.mTvItemNotLoggedInLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("flag", "me");
                    startActivity(intent);
                }
            });

            notLoggedInViewHolder.mTvItemNotLoggedInRegister.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getActivity(), RegisterActivity.class));
                }
            });
            mTvExit.setVisibility(View.GONE);
        }
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
                && !Build.BRAND.toLowerCase().contains("essential")) {
            // Essential Phone 不支持沉浸式，否则系统又不从状态栏下方开始布局又给你下发 WindowInsets
            CollapsingToolbarLayout.LayoutParams params = (CollapsingToolbarLayout.LayoutParams) titleTv.getLayoutParams();
            params.topMargin = BarUtils.getStatusBarHeight();
            titleTv.setLayoutParams(params);
        }
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getMyInfo();
            }
        });
        mRyMe.setNestedScrollingEnabled(false);
        mRyMe.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
    }


    private void initData() {
        String config = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");
        if (!TextUtils.isEmpty(config)) {
            try {
                Gson gson = new Gson();
                ConfigBean.DataBean dataBean = gson.fromJson(config, ConfigBean.DataBean.class);
                String meItems = new String(EncodeUtils.base64Decode(dataBean.getFunctionsconfig2()));
                LogUtils.dTag("MeFragment==", " meItems == " + meItems);
                Type typeToken = new TypeToken<List<MeItemBean>>() {
                }.getType();
                mMeItemBeans = gson.fromJson(meItems, typeToken);
                for (int i = 0; i < mMeItemBeans.size(); i++) {
                    mMeItemBeans.get(i).setMessage(0);
                    if (mMeItemBeans.get(i).getFunName().equals("xxzx")) {
                        messageFunName = "xxzx";
                        messagePosition = i;
                    }
                }
                mAdapter = new MeItemAdapter(R.layout.item_me, mMeItemBeans);
                mRyMe.setAdapter(mAdapter);

                mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        String funName = mAdapter.getItem(position).getFunName();
                        String url = mAdapter.getItem(position).getUrl();

                        if (funName.equals("gy")) {
                            //关于
                            startActivity(new Intent(getActivity(), AboutUsActivity.class));
                            return;
                        }
                        if (isLogin) {
                            if (funName.equals("sjtb")) {
                                //数据同步
                                startActivity(new Intent(getActivity(), BindYGActivity.class));
                            } else if (funName.equals("aqzx")) {
                                //安全中心
                                startActivity(new Intent(getActivity(), AccountAndSafeActivity.class));
                            } else if (funName.equals("xxzx")) {
                                //消息中心
                                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                            } else if (funName.equals("shdz")) {
                                //收货地址
                                startActivity(new Intent(getActivity(), ShippingAddressActivity.class));
                            } else if (funName.equals("yhk")) {
                                //银行卡
                                startActivity(new Intent(getActivity(), BankCardActivity.class));
                            } else if (funName.equals("yjfk")) {
                                //意见反馈
                                startActivity(new Intent(getActivity(), FeedBackActivity.class));
                            } else if (funName.equals("separator")) {
                                //分割线
                            } else {
                                String stitchingUrl;
                                String params = UrlUtils.getUrlParamsByMap(Params.getMeItemStitchingParams());
                                if (!TextUtils.isEmpty(url)) {
                                    //将返回的url和参数拼接
                                    if (url.contains("?")) {
                                        if (url.endsWith("?")) {
                                            stitchingUrl = url + params;
                                        } else {
                                            stitchingUrl = url + "&" + params;
                                        }
                                    } else {
                                        stitchingUrl = url + "?" + params;
                                    }
                                    toWebActivity(stitchingUrl);
                                } else {
                                    ToastUtils.showShort(getResources().getString(R.string.str_function_not_not_open));
                                }
                            }
                        } else {
                            ToastUtils.showShort(getResources().getString(R.string.str_please_login_then_sys_yg));
                        }
                    }
                });
            } catch (Exception e) {
                LogUtils.e(e.getMessage());
            }
        }

        mTvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).clear();
                boolean isauth = UMShareAPI.get(getActivity()).isAuthorize(getActivity(), SHARE_MEDIA.QQ);
                if (isauth) {
                    UMShareAPI.get(getActivity()).deleteOauth(getActivity(), SHARE_MEDIA.QQ, authListener);
                }
                //清除用户配置信息
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.putExtra("flag", "exit");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                getActivity().finish();
            }
        });

    }

    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {

        }
    };

    private void getMyInfo() {
        if (isLogin) {
            showLoading();
            OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getMyUrl(), NETWORK_GET_MY, Params.getMyParams());
        }
    }

    /**
     * 跳转到webActivity
     *
     * @param url
     */
    private void toWebActivity(String url) {
        Intent intent = new Intent(getActivity(), WebActivity.class);
        intent.putExtra(Constant.TO_WEBVIEW_URL, url);
        startActivity(intent);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            QMUIStatusBarHelper.setStatusBarDarkMode(getActivity());
            getMyInfo();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        getMyInfo();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("MeFragment== onSuccessResponse==", "onSuccessResponse== requestCode = " + requestCode + " response = " + response);
        dissmissDialog();
        refreshLayout.finishRefresh();
        try {
            MyInfoBean myInfoBean = new Gson().fromJson(response, MyInfoBean.class);
            if (myInfoBean.getResult() > 0) {
                //保存开通支付密码类型
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NOT_PWD_PAY_TYPE, String.valueOf(myInfoBean.getData().getNotpwdpaytype()));

                //最高免密支付金额
                double maxnotpwd = myInfoBean.getData().getMaxnotpwd();
                //未读消息
                int newmailnum = myInfoBean.getData().getNewmailnum();

                if (!TextUtils.isEmpty(messageFunName)) {
                    //重新设置消息中心那一栏的消息数量
                    mAdapter.getItem(messagePosition).setMessage(newmailnum);
                    mAdapter.notifyDataSetChanged();
                }
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    class LoggedInViewHolder {
        @BindView(R.id.iv_item_logged_in_head)
        QMUIRadiusImageView mIvItemLoggedInHead;
        @BindView(R.id.tv_item_logged_in_nickname)
        TextView mTvItemLoggedInNickname;
        @BindView(R.id.tv_item_logged_in_number)
        TextView mTvItemLoggedInNumber;
        @BindView(R.id.ll_item_logged_in)
        LinearLayout mLlItemLoggedIn;

        LoggedInViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    class NotLoggedInViewHolder {
        @BindView(R.id.tv_item_not_logged_in_login)
        TextView mTvItemNotLoggedInLogin;
        @BindView(R.id.tv_item_not_logged_in_register)
        TextView mTvItemNotLoggedInRegister;

        NotLoggedInViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

}
